//
//  ViewController.swift
//  GoldStar
//
//  Created by TRS-Mobile on 2025/6/24.
//

import UIKit
import ChameleonFramework
import RxSwift
import RxCocoa
import SnapKit
import SFSafeSymbols
import SwiftyUserDefaults

class ViewController: BaseViewController {
    
    let mainVM: MainViewModel = MainViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        makeUI()
        bindUI()
    }
    
    func bindUI() {
        
        let addButton = UIBarButtonItem(image: UIImage.paletteSFSymbolImage(.personBadgePlus), style: .plain, target: nil, action: nil)
        navigationItem.rightBarButtonItem = addButton
        
        let add = addButton.rx.tap
            .flatMapLatest(showNameInputAlert)
            .compactMap{$0}
            .filter {!$0.isEmpty}
        
        let deleteItem = UIBarButtonItem(image: UIImage.paletteSFSymbolImage(.personBadgeMinus), style: .plain, target: nil, action: nil)
        navigationItem.leftBarButtonItem = deleteItem
        
        let delete = deleteItem.rx.tap
            .flatMapLatest(deleteAlert)
            .filter { $0 }
        
        let input = MainViewModel.Input(userName: add,
                                        deleteTrigger: delete)
        let out = mainVM.transform(input: input)
        
        out.users
            .bind(to: tableView.rx.items(cellIdentifier: "UserTableViewCell", cellType: UserTableViewCell.self)) {index,user,cell in
                cell.bind(to: user)
            }
            .disposed(by: disposeBag)
        out.users
            .map { !$0.isEmpty }
            .bind(to: deleteItem.rx.isEnabled)
            .disposed(by: disposeBag)
    }

    func makeUI() -> Void {
        
        view.backgroundColor = UIColor(hexString: "#4CAF50")
        
        // 添加表格视图
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func showNameInputAlert() -> Observable<String?> {
        return Observable.create { [weak self] observer in
            guard let self = self else {
                observer.onCompleted()
                return Disposables.create()
            }
            
            let alert = UIAlertController(title: "请输入姓名", message: nil, preferredStyle: .alert)
            
            // 确定按钮 - 发送输入文本
            let confirmAction = UIAlertAction(title: "确定", style: .default) { _ in
                let name = alert.textFields?.first?.text
                observer.onNext(name) // 发送输入值
                observer.onCompleted()
            }
            
            // 添加输入框
            alert.addTextField { textField in
                textField.placeholder = "姓名"
                textField.rx.text.orEmpty
                    .map { !$0.isEmpty }
                    .bind(to: confirmAction.rx.isEnabled)
                    .disposed(by: self.disposeBag)
            }
            
            // 取消按钮 - 发送完成信号
            let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
                observer.onCompleted()
            }
            
            alert.addAction(confirmAction)
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
            
            return Disposables.create {
                alert.dismiss(animated: true) // 清理时关闭弹窗
            }
        }
    }
    
    func deleteAlert() -> Observable<Bool> {
        return Observable.create { [weak self] observer in
            guard let self = self else {
                observer.onCompleted()
                return Disposables.create()
            }
            
            let alert = UIAlertController(title: "是否删除全部？", message: nil, preferredStyle: .alert)
            
            // 确定按钮 - 发送输入文本
            let confirmAction = UIAlertAction(title: "确定", style: .default) { _ in
                observer.onNext(true) // 发送输入值
                observer.onCompleted()
            }
            
            // 取消按钮 - 发送完成信号
            let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
                observer.onCompleted()
            }
            
            alert.addAction(confirmAction)
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
            
            return Disposables.create {
                alert.dismiss(animated: true) // 清理时关闭弹窗
            }
        }
    }
    
    // 懒加载表格视图
    private lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.register(UserTableViewCell.self, forCellReuseIdentifier: "UserTableViewCell")
        tv.backgroundColor = .clear
        tv.separatorStyle = .none
        tv.rowHeight = UITableView.automaticDimension
        tv.estimatedRowHeight = 100
        return tv
    }()
}

